> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/jaypopat/cf_ai_duet/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloudflare Worker

> Set up the Cloudflare Worker for AI agent and sandbox features

The Cloudflare Worker provides AI agent capabilities and sandbox execution for Duet. It acts as a load balancer that distributes requests to Durable Objects (one per room).

## Architecture

The Worker uses several Cloudflare services:

* **Cloudflare Workers** - Request routing and API endpoints
* **Durable Objects** - Per-room LLM context and memory
* **Cloudflare AI (Llama)** - AI inference for the agent
* **Cloudflare Sandboxes** - Isolated command execution environment

<Note>
  Sandbox features require a paid Cloudflare plan. AI inference and Durable Objects work on the free tier.
</Note>

## Prerequisites

* Cloudflare account
* Wrangler CLI installed
* Bun or Node.js for local development

## Setup

<Steps>
  <Step title="Navigate to worker directory">
    ```bash theme={null}
    cd cf-worker
    ```
  </Step>

  <Step title="Install dependencies">
    <CodeGroup>
      ```bash Bun theme={null}
      bun install
      ```

      ```bash npm theme={null}
      npm install
      ```

      ```bash pnpm theme={null}
      pnpm install
      ```
    </CodeGroup>
  </Step>

  <Step title="Configure wrangler.toml">
    The `wrangler.toml` file is already configured with:

    ```toml theme={null}
    name = "duet-cf-worker"
    main = "index.ts"
    compatibility_date = "2025-12-13"
    compatibility_flags = ["nodejs_compat"]

    [durable_objects]
    bindings = [
      { name = "DUET_AGENT", class_name = "DuetAgent" },
      { name = "Sandbox", class_name = "Sandbox" },
    ]

    [ai]
    binding = "AI"
    ```

    Update the `name` field to your desired Worker name.
  </Step>

  <Step title="Deploy to Cloudflare">
    Deploy the Worker:

    ```bash theme={null}
    bunx wrangler deploy
    ```

    Or with npm:

    ```bash theme={null}
    npx wrangler deploy
    ```

    After deployment, you'll receive a Worker URL like:

    ```
    https://duet-cf-worker.<subdomain>.workers.dev
    ```
  </Step>
</Steps>

## Local Development

To run the Worker locally for development:

```bash theme={null}
bunx wrangler dev --port 8788
```

<Note>
  When running locally, AI inference still happens on Cloudflare's edge, not locally.
</Note>

## Worker Configuration

### Durable Objects

The Worker uses two Durable Objects:

1. **DuetAgent** - Manages per-room chat history and AI context
   * Stores the last 20 messages for context
   * Handles AI inference requests
   * Maintains conversation state

2. **Sandbox** - Provides isolated command execution
   * One sandbox instance per room
   * Allows AI agent to run commands
   * Supports direct command execution by users

### Migrations

Durable Object migrations are configured in `wrangler.toml`:

```toml theme={null}
[[migrations]]
tag = "v1"
new_sqlite_classes = ["DuetAgent"]

[[migrations]]
tag = "v2"
new_sqlite_classes = ["Sandbox"]
```

### Container Configuration

The Sandbox Durable Object uses a custom container:

```toml theme={null}
[[containers]]
class_name = "Sandbox"
image = "./Dockerfile"
```

## API Endpoints

The Worker exposes the following endpoints:

### Health Check

```bash theme={null}
GET /health
```

Returns `ok` if the Worker is running.

### Room Messages

```bash theme={null}
POST /api/rooms/{roomId}/messages
```

Send a message to the AI agent for a specific room.

### Sandbox Execution

```bash theme={null}
POST /api/rooms/{roomId}/sandbox/exec
```

Execute a command in the room's sandbox.

### Room Cleanup

```bash theme={null}
DELETE /api/rooms/{roomId}
```

Clean up a room and its associated Durable Objects.

## Usage with Duet Server

After deploying, use your Worker URL when starting the Duet Go server:

```bash theme={null}
./duet -worker https://duet-cf-worker.<subdomain>.workers.dev
```

Or in your Docker deployment:

```dockerfile theme={null}
CMD ["/app/duet", "-addr", ":2222", "-hostkey", "/app/.ssh/id_ed25519", "-worker", "https://your-worker.workers.dev"]
```

## Monitoring

Observability is configured in `wrangler.toml`:

```toml theme={null}
[observability]
[observability.logs]
enabled = false
head_sampling_rate = 1
invocation_logs = true
persist = true
```

Enable logs in production by setting `enabled = true`.

## Troubleshooting

<Warning>
  If sandbox features aren't working, verify you have a paid Cloudflare plan that supports Workers with Containers.
</Warning>

### Common Issues

* **404 errors**: Ensure room ID is included in the request path
* **Sandbox not available**: Check if you have a paid Cloudflare plan
* **AI inference failing**: Verify AI binding is configured in wrangler.toml
* **Durable Objects not persisting**: Check migrations are applied correctly
